package utils

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"runtime"
	"time"
)

func MongoClient(dsn string) (*mongo.Client, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	cpuNum := uint64(runtime.NumCPU())
	opt := options.Client().ApplyURI(dsn)
	opt.SetMinPoolSize(cpuNum)
	opt.SetMaxPoolSize(cpuNum * 4)
	return mongo.Connect(ctx, opt)
}

func MongoPing(client *mongo.Client) error {
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()
	return client.Ping(ctx, readpref.Primary())
}
